﻿using System.Text;
using System.Web;
using Utilities;
using Website.Interfaces;

namespace Website.Infrastructure
{
    public class RedirectionManager  : IRedirectionManager
    {
        public bool RedirectionRequired(HttpRequestBase request)
        {
            bool isComDomain = request.Url.Host.EndsWith(".com");

            return (isComDomain && DutchLanguagePreferred(request) ||
                    !isComDomain && LanguagePreferenceSetInCookie(request, "en-US"));
        }

        private bool DutchLanguagePreferred(HttpRequestBase request)
        {
            if (LanguagePreferenceSetInCookie(request, "nl-NL"))
                return true;

            return LanguagePreferenceSetInMimeHeader(request);
        }

        private bool LanguagePreferenceSetInCookie(HttpRequestBase request, string language)
        {
            return (request.Cookies["SiteLanguage"] != null &&
                    request.Cookies["SiteLanguage"].Value.ToLower() == language.ToLower());
        }

        private bool LanguagePreferenceSetInMimeHeader(HttpRequestBase request)
        {
            string acceptLanguage = request.Headers["Accept-Language"];
            return (acceptLanguage != null &&
                    String1OccursBeforeString2(acceptLanguage.ToLower(), "nl-nl", "en-us"));
        }

        public string GetAlternateSiteUrl(HttpRequestBase request)
        {
            var url = request.Url;
            if (url.Host.ToLower().EndsWith("com"))
            {
                return url.ReplaceTopLevelDomain("com", "nl").ToString();
            }

            return url.ReplaceTopLevelDomain("nl", "com").ToString();
        }

        private bool String1OccursBeforeString2(string contents, string str1, string str2)
        {
            int idx1 = contents.IndexOf(str1);
            int idx2 = contents.IndexOf(str2);

            if (idx1 == -1)
            {
                return false;
            }

            if (idx2 == -1)
            {
                return true;
            }

            return (idx1 < idx2);
        }
    }
}
